package com.example.statelayouthelper;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class Demo1Adapter extends RecyclerView.Adapter<Demo1Adapter.MyViewHolder> {
    private final List<String> list;
    private final Context context;
    ItemClickListener mItemClickListener;

    public Demo1Adapter(List<String> list, Context context) {
        this.list = list;
        this.context = context;
    }

    public void setOnItemClickListener(ItemClickListener listener) {
        this.mItemClickListener = listener;
    }

    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View inflate = LayoutInflater.from(context).inflate(R.layout.item_demo1, parent, false);
        return new MyViewHolder(inflate, mItemClickListener);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, final int position) {
        if (list != null && list.size() > 0) {
            holder.tv_item.setText(list.get(position));
        }
    }

    @Override
    public int getItemCount() {
        return list == null ? 0 : list.size();
    }

    public static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        private final TextView tv_item;
        private final ItemClickListener mListener;

        public MyViewHolder(View view, ItemClickListener listener) {
            super(view);
            tv_item = view.findViewById(R.id.tv_item);
            this.mListener = listener;
            view.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            if (mListener != null) {
                mListener.onItemClick(view, getPosition());
            }
        }
    }

}
